package com.dayu.finecomm.protocol.hd72;

import io.netty.buffer.ByteBuf;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dayu.finecomm.protocol.codec.Protocol;
import com.dayu.finecomm.protocol.codec.UDPPacketFrameDecoder;
import com.dayu.finecomm.protocol.pojo.TPacket;
import com.dayu.finecomm.protocol.pojo.TPacket.VType;

@Protocol(CommandResultDecoder.PROTO)
public class CommandResultDecoder extends UDPPacketFrameDecoder<TPacket> {

	static final String PROTO = "HD72";

	static Logger LOGGER = LoggerFactory.getLogger(CommandResultDecoder.class);

	static int ST_MAGIC_START = 0x53543A; // ST:
	static int ST_MAGIC_END = 0x2E; // 回车换行

	static String STR_KV = ";([^:]+):(-?\\d+(\\.\\d*+)?)"; // ;P1:25326380

	static Pattern KV = Pattern.compile(STR_KV);
	static Pattern ST = Pattern.compile("^ST:([0-9]+);(.*?).$");

	// ST:00553;14/10/29
	// 22:59;P1:25326380;P2:25313712;K5:0;A1:775.1;A2:0.205;H:341.

	public CommandResultDecoder() {
		super("ST:", ".", 4);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.dayu.protocol.hd72.ProtocolDecoder#unpack(java.lang.String)
	 */
	@Override
	public TPacket unpack(ByteBuf in) {

		String packet = in.toString(com.dayu.finecomm.utils.Helpers.ASCII);

		Matcher m = ST.matcher(packet);

		if (m.find()) {

			int sn = NumberUtils.toInt(m.group(1));

			long timestamp = new Date().getTime();

			TPacket s = new TPacket(VType.RRR, PROTO, sn, timestamp);
			s.result = m.group(2);

			return s;
		}

		return null;

	}

	@Override
	public byte[] echo() {
		return "@222".getBytes();
	}

}
